package com.lynn.springboot_demo.test;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;

import java.awt.*;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

/**
 * @author cl
 * @Date 2020/9/9 10:09
 * <p>
 * pdf加水印
 */
public class PdfWaterDrop {

    public static void main(String[] args) throws DocumentException, IOException {
        // 要输出的pdf文件
        BufferedOutputStream outPath = new BufferedOutputStream(new FileOutputStream(new File("C:\\Users\\Administrator\\Desktop\\res.pdf")));
        // 将pdf文件先加水印然后输出
        setWatermark(outPath, "G:\\新文书\\1515\\2004\\C\\总队\\0001\\1515-2004-C-总队-0001.PDF");
    }

    public static void setWatermark(BufferedOutputStream bos, String input)
            throws DocumentException, IOException {
        PdfReader reader = new PdfReader(input);
        PdfStamper stamper = new PdfStamper(reader, bos);
        int total = reader.getNumberOfPages() + 1;
        PdfContentByte content;
        BaseFont base = BaseFont.createFont("static/Font/simfang.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        PdfGState gs = new PdfGState();
        for (int i = 1; i < total; i++) {
            content = stamper.getOverContent(i);// 在内容上方加水印
//             content = stamper.getUnderContent(i);//在内容下方加水印
            gs.setFillOpacity(0.5f);
            // content.setGState(gs);
            content.beginText();
            content.setColorFill(BaseColor.LIGHT_GRAY);
            content.setFontAndSize(base, 40);
            content.setTextMatrix(70, 200);
            content.showTextAligned(Element.ALIGN_CENTER, "公司内部文件，请注意保密！", 300, 400     , 50);
           /* content.setColorFill(BaseColor.BLACK);
            content.setFontAndSize(base, 8);
            content.endText();*/

        }
        stamper.close();
    }
}
